import React, { useState, useEffect } from 'react';
import { 
  Button, 
  Input, 
  Label, 
  Text, 
  Table, 
  TableHeader, 
  TableRow, 
  TableHead, 
  TableBody, 
  TableCell, 
  Tabs, 
  TabsContent, 
  TabsList, 
  TabsTrigger, 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogFooter,
  Select, 
  Checkbox,
  Spinner,
  Badge
} from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import AttendanceSignIn from '../components/AttendanceSignIn';
import {
  AttendanceRecord,
  AttendanceStatus,
  LeaveRequest,
  AttendanceStatistics,
  mockAttendanceRecords,
  mockLeaveRequests,
  saveAttendanceRecord,
  updateAttendanceRecord,
  deleteAttendanceRecord,
  approveLeaveRequest,
  rejectLeaveRequest,
  getAttendanceStatistics
} from '../mock/attendanceData';
import { mockGradeData } from '../mock/gradeData';
import { mockCourses } from '../mock/courseData';

// 定义课程选项类型
interface CourseOption {
  value: string;
  label: string;
}

// 状态样式映射
const statusStyles: Record<AttendanceStatus, string> = {
  present: 'bg-green-100 text-green-800',
  absent: 'bg-red-100 text-red-800',
  leave: 'bg-blue-100 text-blue-800',
  late: 'bg-yellow-100 text-yellow-800'
};

// 状态中文映射
const statusLabels: Record<AttendanceStatus, string> = {
  present: '出勤',
  absent: '缺勤',
  leave: '请假',
  late: '迟到'
};

// 请假状态样式映射
const leaveStatusStyles: Record<string, string> = {
  pending: 'bg-yellow-100 text-yellow-800',
  approved: 'bg-green-100 text-green-800',
  rejected: 'bg-red-100 text-red-800'
};

// 请假状态中文映射
const leaveStatusLabels: Record<string, string> = {
  pending: '待审批',
  approved: '已批准',
  rejected: '已拒绝'
};

export default function AttendanceManagementPage() {
  const { session } = useSession();
  const [activeTab, setActiveTab] = useState('records');
  const [attendanceRecords, setAttendanceRecords] = useState<AttendanceRecord[]>([]);
  const [filteredRecords, setFilteredRecords] = useState<AttendanceRecord[]>([]);
  const [leaveRequests, setLeaveRequests] = useState<LeaveRequest[]>([]);
  const [statistics, setStatistics] = useState<AttendanceStatistics[]>([]);
  
  // 表单状态
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCourse, setSelectedCourse] = useState('');
  const [selectedDate, setSelectedDate] = useState('');
  
  // 模态框状态
  const [isSignInOpen, setIsSignInOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [isBatchDeleteOpen, setIsBatchDeleteOpen] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<AttendanceRecord | null>(null);
  const [currentLeaveRequest, setCurrentLeaveRequest] = useState<LeaveRequest | null>(null);
  
  // 加载状态
  const [loading, setLoading] = useState(false);
  
  // 课程选项
  const [courseOptions, setCourseOptions] = useState<CourseOption[]>([]);
  
  // 批量选择状态
  const [selectedRecords, setSelectedRecords] = useState<string[]>([]);
  const [selectAll, setSelectAll] = useState(false);
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalPages, setTotalPages] = useState(1);
  const [paginatedRecords, setPaginatedRecords] = useState<AttendanceRecord[]>([]);

  // 初始化数据
  useEffect(() => {
    loadData();
    loadCourseOptions();
  }, []);
  
  // 当筛选条件或分页参数变化时重新计算分页数据
  useEffect(() => {
    calculatePagination();
  }, [filteredRecords, currentPage, pageSize]);
  
  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 过滤出勤记录
      let filteredRecords = [...mockAttendanceRecords];
      if (selectedCourse) {
        filteredRecords = filteredRecords.filter(record => record.courseId === selectedCourse);
      }
      if (selectedDate) {
        filteredRecords = filteredRecords.filter(record => record.date === selectedDate);
      }
      if (searchQuery) {
        filteredRecords = filteredRecords.filter(record => 
          record.studentName.includes(searchQuery) || 
          record.studentId.includes(searchQuery) ||
          record.courseName.includes(searchQuery)
        );
      }
      
      setFilteredRecords(filteredRecords);
      setLeaveRequests([...mockLeaveRequests]);
      const statisticsData = await getAttendanceStatistics();
      setStatistics(statisticsData);
      
      // 重置分页
      setCurrentPage(1);
      // 重置选择状态
      setSelectedRecords([]);
      setSelectAll(false);
    } catch (error) {
      console.error('加载数据失败:', error);
      alert('加载数据失败，请重试');
    } finally {
      setLoading(false);
    }
  };
  
  // 计算分页数据
  const calculatePagination = () => {
    const totalItems = filteredRecords.length;
    const totalPages = Math.ceil(totalItems / pageSize);
    setTotalPages(totalPages);
    
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredRecords.slice(startIndex, endIndex);
    setPaginatedRecords(paginatedData);
  };
  
  // 加载课程选项
  const loadCourseOptions = () => {
    // 从成绩数据中提取唯一的课程
    const uniqueCourses = new Map<string, string>();
    mockGradeData.forEach(grade => {
      if (grade.courseName && grade.courseId) {
        uniqueCourses.set(grade.courseId, grade.courseName);
      }
    });
    
    const options: CourseOption[] = Array.from(uniqueCourses.entries()).map(([id, name]) => ({
      value: id,
      label: name
    }));
    
    setCourseOptions(options);
  };
  
  // 处理搜索
  const handleSearch = () => {
    loadData();
  };
  
  // 重置筛选
  const handleReset = () => {
    setSearchQuery('');
    setSelectedCourse('');
    setSelectedDate('');
    loadData();
  };
  
  // 打开签到对话框
  const handleOpenSignIn = (courseId: string, courseName: string, date: string) => {
    setSelectedCourse(courseId);
    setSelectedDate(date || new Date().toISOString().split('T')[0]);
    setIsSignInOpen(true);
  };
  
  // 关闭签到对话框
  const handleCloseSignIn = () => {
    setIsSignInOpen(false);
    loadData(); // 重新加载数据以显示最新的签到记录
  };
  
  // 处理签到成功
  const handleSignInSuccess = () => {
    setIsSignInOpen(false);
    loadData();
  };
  
  // 打开编辑对话框
  const handleOpenEdit = (record: AttendanceRecord) => {
    setCurrentRecord({...record});
    setIsEditOpen(true);
  };
  
  // 关闭编辑对话框
  const handleCloseEdit = () => {
    setIsEditOpen(false);
    setCurrentRecord(null);
  };
  
  // 保存编辑后的记录
  const handleSaveEdit = async () => {
    if (!currentRecord) return;
    
    try {
      await updateAttendanceRecord(currentRecord.id, currentRecord);
      alert('修改成功');
      handleCloseEdit();
      loadData();
    } catch (error) {
      console.error('保存失败:', error);
      alert('保存失败，请重试');
    }
  };
  
  // 打开删除对话框
  const handleOpenDelete = (record: AttendanceRecord) => {
    setCurrentRecord(record);
    setIsDeleteOpen(true);
  };
  
  // 关闭删除对话框
  const handleCloseDelete = () => {
    setIsDeleteOpen(false);
    setCurrentRecord(null);
  };
  
  // 确认删除
  const handleConfirmDelete = async () => {
    if (!currentRecord) return;
    
    try {
      await deleteAttendanceRecord(currentRecord.id);
      alert('删除成功');
      handleCloseDelete();
      loadData();
    } catch (error) {
      console.error('删除失败:', error);
      alert('删除失败，请重试');
    }
  };
  
  // 处理请假审批
  const handleApproveLeave = async (request: LeaveRequest) => {
    try {
      await approveLeaveRequest(request.id, session?.user.name || '管理员');
      alert('已批准请假');
      loadData();
    } catch (error) {
      console.error('审批失败:', error);
      alert('审批失败，请重试');
    }
  };
  
  // 处理请假拒绝
  const handleRejectLeave = async (request: LeaveRequest) => {
    try {
      await rejectLeaveRequest(request.id, session?.user.name || '管理员');
      alert('已拒绝请假');
      loadData();
    } catch (error) {
      console.error('操作失败:', error);
      alert('操作失败，请重试');
    }
  };
  
  // 处理记录选择
  const handleSelectRecord = (recordId: string, checked: boolean) => {
    if (checked) {
      setSelectedRecords(prev => [...prev, recordId]);
    } else {
      setSelectedRecords(prev => prev.filter(id => id !== recordId));
    }
    
    // 如果取消选择某条记录，取消全选状态
    if (!checked) {
      setSelectAll(false);
    }
  };
  
  // 处理全选
  const handleSelectAll = (checked: boolean) => {
    setSelectAll(checked);
    if (checked) {
      setSelectedRecords(paginatedRecords.map(record => record.id));
    } else {
      setSelectedRecords([]);
    }
  };
  
  // 打开批量删除对话框
  const handleOpenBatchDelete = () => {
    setIsBatchDeleteOpen(true);
  };
  
  // 关闭批量删除对话框
  const handleCloseBatchDelete = () => {
    setIsBatchDeleteOpen(false);
  };
  
  // 确认批量删除
  const handleConfirmBatchDelete = async () => {
    try {
      for (const recordId of selectedRecords) {
        await deleteAttendanceRecord(recordId);
      }
      alert(`成功删除 ${selectedRecords.length} 条记录`);
      handleCloseBatchDelete();
      setSelectedRecords([]);
      setSelectAll(false);
      loadData();
    } catch (error) {
      console.error('批量删除失败:', error);
      alert('批量删除失败，请重试');
    }
  };
  
  // 处理分页
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    // 切换页码时清空选择状态
    setSelectedRecords([]);
    setSelectAll(false);
  };
  
  // 处理每页显示数量变化
  const handlePageSizeChange = (size: number) => {
    setPageSize(size);
    setCurrentPage(1); // 重置为第一页
    // 清空选择状态
    setSelectedRecords([]);
    setSelectAll(false);
  };
  
  // 渲染搜索和筛选区域
  const renderSearchFilter = () => (
    <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <div className="md:col-span-2">
        <Label htmlFor="search">搜索 (学生姓名/学号/课程名称)</Label>
        <div className="flex space-x-2 mt-1">
          <Input
            id="search"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="输入搜索内容"
            className="flex-1"
          />
          <Button onClick={handleSearch}>搜索</Button>
        </div>
      </div>
      <div>
        <Label htmlFor="course">选择课程</Label>
        <Select
          id="course"
          value={selectedCourse}
          onChange={(e) => setSelectedCourse(e.target.value)}
          className="w-full mt-1"
        >
          <option value="">全部课程</option>
          {courseOptions.map(option => (
            <option key={option.value} value={option.value}>{option.label}</option>
          ))}
        </Select>
      </div>
      <div>
        <Label htmlFor="date">选择日期</Label>
        <Input
          id="date"
          type="date"
          value={selectedDate}
          onChange={(e) => setSelectedDate(e.target.value)}
          className="w-full mt-1"
        />
      </div>
      {selectedCourse || selectedDate || searchQuery ? (
        <Button onClick={handleReset} variant="ghost" className="mt-4">
          重置筛选
        </Button>
      ) : null}
      
      {/* 批量删除按钮 */}
      {selectedRecords.length > 0 && (
        <Button 
          onClick={handleOpenBatchDelete} 
          variant="destructive" 
          className="mt-4"
        >
          批量删除 ({selectedRecords.length})
        </Button>
      )}
    </div>
  );
  
  // 渲染出勤记录表格
  const renderAttendanceTable = () => (
    <>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-12">
              <Checkbox
                checked={selectAll && paginatedRecords.length > 0}
                onCheckedChange={(checked) => handleSelectAll(checked as boolean)}
                aria-label="全选"
              />
            </TableHead>
            <TableHead>学生姓名</TableHead>
            <TableHead>学号</TableHead>
            <TableHead>课程名称</TableHead>
            <TableHead>日期</TableHead>
            <TableHead>时间</TableHead>
            <TableHead>状态</TableHead>
            <TableHead>原因</TableHead>
            <TableHead>记录人</TableHead>
            <TableHead>操作</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {loading ? (
            <TableRow>
              <TableCell colSpan={10} className="flex justify-center">
                <div className="flex items-center">
                  <Spinner className="mr-2" />
                  <Text>加载中...</Text>
                </div>
              </TableCell>
            </TableRow>
          ) : paginatedRecords.length === 0 ? (
            <TableRow>
              <TableCell colSpan={10} className="text-center">
                暂无数据
              </TableCell>
            </TableRow>
          ) : (
            paginatedRecords.map((record) => (
              <TableRow key={record.id}>
                <TableCell>
                  <Checkbox
                    checked={selectedRecords.includes(record.id)}
                    onCheckedChange={(checked) => handleSelectRecord(record.id, checked as boolean)}
                    aria-label={`选择${record.studentName}`}
                  />
                </TableCell>
                <TableCell>{record.studentName}</TableCell>
                <TableCell>{record.studentId}</TableCell>
                <TableCell>{record.courseName}</TableCell>
                <TableCell>{record.date}</TableCell>
                <TableCell>{record.startTime} - {record.endTime}</TableCell>
                <TableCell>
                  <Badge className={statusStyles[record.status]}>
                    {statusLabels[record.status]}
                  </Badge>
                </TableCell>
                <TableCell>{record.reason || '-'}</TableCell>
                <TableCell>{record.recordedBy}</TableCell>
                <TableCell className="flex space-x-2">
                  <Button onClick={() => handleOpenEdit(record)} variant="ghost" size="sm">
                    编辑
                  </Button>
                  <Button 
                    onClick={() => handleOpenDelete(record)} 
                    variant="ghost" 
                    size="sm" 
                    className="text-red-600"
                  >
                    删除
                  </Button>
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
      
      {/* 分页控件 */}
      {!loading && paginatedRecords.length > 0 && (
        <div className="flex flex-col md:flex-row justify-between items-center mt-4">
          <div className="mb-4 md:mb-0">
            <span className="text-sm text-gray-500">
              显示第 {(currentPage - 1) * pageSize + 1} 到 {Math.min(currentPage * pageSize, filteredRecords.length)} 条，共 {filteredRecords.length} 条
            </span>
          </div>
          <div className="flex items-center space-x-2">
            <Label htmlFor="pageSize">每页显示:</Label>
            <Select
              id="pageSize"
              value={pageSize.toString()}
              onChange={(e) => handlePageSizeChange(Number(e.target.value))}
              className="w-24"
            >
              <option value="5">5条</option>
              <option value="10">10条</option>
              <option value="20">20条</option>
              <option value="50">50条</option>
            </Select>
            <div className="flex space-x-1">
              <Button
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
                size="sm"
              >
                上一页
              </Button>
              {Array.from({ length: totalPages }, (_, i) => i + 1)
                .filter(page => 
                  page === 1 || 
                  page === totalPages || 
                  (page >= currentPage - 1 && page <= currentPage + 1)
                )
                .map((page, index, array) => {
                  // 添加省略号
                  if (index > 0 && array[index - 1] !== page - 1) {
                    return (
                      <span key={`ellipsis-${page}`} className="flex items-center px-2">...</span>
                    );
                  }
                  return (
                    <Button
                      key={page}
                      onClick={() => handlePageChange(page)}
                      variant={currentPage === page ? "default" : "ghost"}
                      size="sm"
                      className={currentPage === page ? "bg-primary" : ""}
                    >
                      {page}
                    </Button>
                  );
                })}
              <Button
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
                size="sm"
              >
                下一页
              </Button>
            </div>
          </div>
        </div>
      )}
    </>
  );
  
  // 查找当前选中的课程名称
  const getSelectedCourseName = () => {
    if (!selectedCourse) return '全部课程';
    const course = courseOptions.find(option => option.value === selectedCourse);
    return course?.label || '全部课程';
  };

  // 渲染请假请求表格
  const renderLeaveRequestsTable = () => (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>学生姓名</TableHead>
          <TableHead>学号</TableHead>
          <TableHead>课程名称</TableHead>
          <TableHead>开始日期</TableHead>
          <TableHead>结束日期</TableHead>
          <TableHead>请假原因</TableHead>
          <TableHead>状态</TableHead>
          <TableHead>申请时间</TableHead>
          <TableHead>操作</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {loading ? (
          <TableRow>
            <TableCell colSpan={9} className="flex justify-center">
              <div className="flex items-center">
                <Spinner className="mr-2" />
                <Text>加载中...</Text>
              </div>
            </TableCell>
          </TableRow>
        ) : leaveRequests.length === 0 ? (
          <TableRow>
            <TableCell colSpan={9} className="text-center">
              暂无请假申请
            </TableCell>
          </TableRow>
        ) : (
          leaveRequests.map((request) => (
            <TableRow key={request.id}>
              <TableCell>{request.studentName}</TableCell>
              <TableCell>{request.studentId}</TableCell>
              <TableCell>{request.courseName}</TableCell>
              <TableCell>{request.startDate}</TableCell>
              <TableCell>{request.endDate}</TableCell>
              <TableCell>{request.reason}</TableCell>
              <TableCell>
                <Badge className={leaveStatusStyles[request.status]}>
                  {leaveStatusLabels[request.status]}
                </Badge>
              </TableCell>
              <TableCell>{request.requestTime}</TableCell>
              <TableCell className="flex space-x-2">
                {request.status === 'pending' && (
                  <>
                    <Button 
                      onClick={() => handleApproveLeave(request)} 
                      variant="ghost" 
                      size="sm" 
                      className="text-green-600"
                    >
                      批准
                    </Button>
                    <Button 
                      onClick={() => handleRejectLeave(request)} 
                      variant="ghost" 
                      size="sm" 
                      className="text-red-600"
                    >
                      拒绝
                    </Button>
                  </>
                )}
                {request.status !== 'pending' && (
                  <Text className="text-gray-500">无需操作</Text>
                )}
              </TableCell>
            </TableRow>
          ))
        )}
      </TableBody>
    </Table>
  );

  // 渲染统计分析
  const renderStatistics = () => (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
      <div className="bg-white p-6 rounded-lg shadow">
        <h3 className="text-lg font-semibold mb-4">出勤统计</h3>
        <div className="grid grid-cols-2 gap-4">
          {statistics && statistics.length > 0 ? (
            statistics.map((stat) => (
              <div key={stat.courseId} className="bg-gray-50 p-4 rounded">
                <Text className="font-medium">{stat.courseName}</Text>
                <div className="space-y-2 mt-2">
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-500">出勤:</span>
                    <span className="text-green-600">{stat.presentCount} ({stat.presentRate}%)</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-500">缺勤:</span>
                    <span className="text-red-600">{stat.absentCount} ({stat.absentRate}%)</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-500">迟到:</span>
                    <span className="text-yellow-600">{stat.lateCount} ({stat.lateRate}%)</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-500">请假:</span>
                    <span className="text-blue-600">{stat.leaveCount} ({stat.leaveRate}%)</span>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="col-span-2 text-center text-gray-500">
              暂无统计数据
            </div>
          )}
        </div>
      </div>
      
      <div className="bg-white p-6 rounded-lg shadow">
        <h3 className="text-lg font-semibold mb-4">学生出勤排行</h3>
        <div className="space-y-3">
          {statistics && statistics.length > 0 && statistics[0].studentRanking && statistics[0].studentRanking.length > 0 ? (
            statistics[0].studentRanking.map((student, index) => (
              <div key={student.studentId} className="flex justify-between items-center p-2">
                <div className="flex items-center">
                  <span className="w-6 h-6 bg-gray-200 rounded-full flex items-center justify-center text-sm font-medium mr-2">
                    {index + 1}
                  </span>
                  <span>{student.studentName}</span>
                </div>
                <div className="flex items-center">
                  <span className="font-semibold text-green-600 mr-2">
                    {student.attendanceRate}%
                  </span>
                  <div className="w-24 bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-green-500 h-2 rounded-full" 
                      style={{ width: `${student.attendanceRate}%` }}
                    ></div>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="text-center text-gray-500">
              暂无排行数据
            </div>
          )}
        </div>
      </div>
    </div>
  );
  
  return (
    <div className="p-6">
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">出勤管理</h1>
          <p className="text-gray-500 mt-1">管理学生出勤记录、请假申请和统计分析</p>
        </div>
        <Button 
          onClick={() => handleOpenSignIn(selectedCourse, getSelectedCourseName(), selectedDate)} 
          className="mt-4 md:mt-0 bg-green-500 hover:bg-green-600"
        >
          课堂签到
        </Button>
      </div>
      
      {renderSearchFilter()}
      
      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="mb-6">
          <TabsTrigger value="records">出勤记录</TabsTrigger>
          <TabsTrigger value="leave">请假管理</TabsTrigger>
          <TabsTrigger value="statistics">统计分析</TabsTrigger>
        </TabsList>
        
        <TabsContent value="records" className="space-y-4">
          {renderAttendanceTable()}
        </TabsContent>
        
        <TabsContent value="leave" className="space-y-4">
          {renderLeaveRequestsTable()}
        </TabsContent>
        
        <TabsContent value="statistics" className="space-y-4">
          {renderStatistics()}
        </TabsContent>
      </Tabs>
      
      {/* 签到对话框 */}
      {isSignInOpen && (
        <AttendanceSignIn 
          courseId={selectedCourse || courseOptions[0]?.value || ''}
          courseName={getSelectedCourseName()}
          date={selectedDate || new Date().toISOString().split('T')[0]}
          onClose={handleCloseSignIn}
          onSuccess={handleSignInSuccess}
        />
      )}
      
      {/* 编辑对话框 */}
      <Dialog open={isEditOpen} onOpenChange={handleCloseEdit}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>编辑出勤记录</DialogTitle>
          </DialogHeader>
          
          {currentRecord && (
            <div className="grid gap-4 py-4">
              <div>
                <Label>学生姓名: {currentRecord.studentName}</Label>
              </div>
              <div>
                <Label>学号: {currentRecord.studentId}</Label>
              </div>
              <div>
                <Label>课程名称: {currentRecord.courseName}</Label>
              </div>
              <div>
                <Label>日期: {currentRecord.date}</Label>
              </div>
              <div>
                <Label htmlFor="status">出勤状态</Label>
                <Select
                  id="status"
                  value={currentRecord.status}
                  onChange={(e) => 
                    setCurrentRecord(prev => prev ? { ...prev, status: e.target.value as AttendanceStatus } : null)
                  }
                  className="w-full mt-1"
                >
                  <option value="present">出勤</option>
                  <option value="absent">缺勤</option>
                  <option value="leave">请假</option>
                  <option value="late">迟到</option>
                </Select>
              </div>
              <div>
                <Label htmlFor="reason">原因/备注</Label>
                <Input
                  id="reason"
                  value={currentRecord.reason || ''}
                  onChange={(e) => 
                    setCurrentRecord(prev => prev ? { ...prev, reason: e.target.value } : null)
                  }
                  placeholder="输入原因或备注"
                  className="w-full mt-1"
                />
              </div>
            </div>
          )}
          
          <DialogFooter>
            <Button onClick={handleCloseEdit}>取消</Button>
            <Button onClick={handleSaveEdit} className="bg-green-500 hover:bg-green-600">
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      
      {/* 删除确认对话框 */}
      <Dialog open={isDeleteOpen} onOpenChange={handleCloseDelete}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
          </DialogHeader>
          
          <p className="py-4">
            确定要删除 {currentRecord?.studentName || ''} 的出勤记录吗？此操作不可恢复。
          </p>
          
          <DialogFooter>
            <Button onClick={handleCloseDelete}>取消</Button>
            <Button 
              onClick={handleConfirmDelete} 
              className="bg-red-500 hover:bg-red-600"
            >
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      
      {/* 批量删除确认对话框 */}
      <Dialog open={isBatchDeleteOpen} onOpenChange={handleCloseBatchDelete}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>批量删除确认</DialogTitle>
          </DialogHeader>
          
          <p className="py-4">
            确定要删除选中的 {selectedRecords.length} 条出勤记录吗？此操作不可恢复。
          </p>
          
          <DialogFooter>
            <Button onClick={handleCloseBatchDelete}>取消</Button>
            <Button 
              onClick={handleConfirmBatchDelete} 
              className="bg-red-500 hover:bg-red-600"
            >
              批量删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}